package cn.cxy.albumselecttoolkit

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.text.TextUtils
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import cn.cxy.albumselecttoolkit.AlbumSelectConstants.EXTRA_CONFIG
import cn.cxy.albumselecttoolkit.AlbumSelectConstants.EXTRA_SELECTED_FILE
import com.donkingliang.imageselector.utils.ImageSelector
import com.qw.soul.permission.SoulPermission
import com.qw.soul.permission.bean.Permission
import com.qw.soul.permission.bean.Permissions
import com.qw.soul.permission.callbcak.CheckRequestPermissionsListener
import com.soundcloud.android.crop.Crop
import top.zibin.luban.CompressionPredicate
import top.zibin.luban.Luban
import top.zibin.luban.OnCompressListener
import java.io.File


class AlbumSelectActivity : AppCompatActivity() {

    private lateinit var croppedImageFile: File
    private lateinit var selectConfig: SelectImageConfig
    private val SELECT_IMAGE_REQUEST_CODE = 0x00000011

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        selectConfig = intent.getParcelableExtra(EXTRA_CONFIG)
        applyPermissionAndSelectImage()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == SELECT_IMAGE_REQUEST_CODE && data != null) {
            val images = data.getStringArrayListExtra(ImageSelector.SELECT_RESULT)
            if (!images.isNullOrEmpty()) {
                val initSelectedImageFile = File(images.first())
                if (selectConfig.cropConfig != null) {
                    croppedImageFile = getNewFile(initSelectedImageFile)
                    cropImage(Uri.fromFile(initSelectedImageFile), Uri.fromFile(croppedImageFile))
                } else {
                    compressImageAndCallback(initSelectedImageFile)
                }
            }
        } else if (requestCode == Crop.REQUEST_CROP && resultCode == Activity.RESULT_OK) {
            compressImageAndCallback(croppedImageFile)
        } else {
            finish()
        }
    }

    private fun compressImageAndCallback(file: File) {
        file.parent?.let {
            if (selectConfig.needCompress) {
                compressImageWithLuban(file, it)
            } else {
                onImageSelected(file)
            }
        }
    }

    private fun getNewFile(file: File): File {
        val newFileName = file.nameWithoutExtension + "_" + System.currentTimeMillis()
            .toString() + "." + file.extension
        return File(file.parent, newFileName)
    }

    private fun selectImage() {
        ImageSelector.builder()
            .setSingle(true) //设置是否单选
            .canPreview(true) //是否点击放大图片查看,，默认为true
            .start(this@AlbumSelectActivity, SELECT_IMAGE_REQUEST_CODE)
    }

    private fun cropImage(sourceImageUri: Uri, destImageUri: Uri) {
        selectConfig.cropConfig?.let {
            Crop.of(sourceImageUri, destImageUri)
                .asSquare().withAspect(it.aspectX, it.aspectY)
                .withMaxSize(it.maxWidth, it.maxHeight)
                .start(this)
        }
    }

    private fun compressImageWithLuban(sourceImageFile: File, targetDir: String) {
        Luban.with(this)
            .load(sourceImageFile)
            .ignoreBy(100)
            .setTargetDir(targetDir)
            .filter(CompressionPredicate { path ->
                !(TextUtils.isEmpty(path) || path.toLowerCase().endsWith(".gif"))
            })
            .setCompressListener(object : OnCompressListener {
                override fun onStart() {}

                override fun onSuccess(file: File?) {
                    onImageSelected(file)
                }

                override fun onError(e: Throwable) {
                    Toast.makeText(this@AlbumSelectActivity, e.message, Toast.LENGTH_LONG).show()
                }
            }).launch()
    }

    private fun onImageSelected(file: File?) {
        file?.let {
            val intent = Intent()
            intent.putExtra(EXTRA_SELECTED_FILE, Uri.fromFile(it))
            this.setResult(Activity.RESULT_OK, intent)
            finish()
        }
    }

    private fun applyPermissionAndSelectImage() {
        SoulPermission.getInstance()
            .checkAndRequestPermissions(
                Permissions.build(
                    Manifest.permission.CAMERA,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
                ),
                object : CheckRequestPermissionsListener {
                    override fun onAllPermissionOk(allPermissions: Array<Permission>) {
                        selectImage() // 打开相册
                    }

                    override fun onPermissionDenied(refusedPermissions: Array<Permission>) {
                    }
                }
            )
    }

}

